<?php

Loader::loadClass('SecurityUtilEx', "modules/HotelBooking/pnincludes");

/**
* //////////////////////////////////////////////////
* auto execute , for initialize config variable
* this function auto call every page has been fetch
*/
function _autoexecute(){

}

function HotelBooking_user_permission()
{
  // Security check
  //we are allow for admin access level , see in config.php variable name ACCESS_EDIT
  if (!SecurityUtil::checkPermission('HotelBooking::', '::', ACCESS_COMMENT)) {
      LogUtil::registerPermissionError(pnModUrl('Users','user','loginscreen'));
  }
}

/**
* smarty template auto call before render
*/
function _preRender(&$render){
  $lang    = FormUtil::getPassedValue ('lang', false , 'GET');
  $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

  $render->assign ('_GET', $_GET);
  $render->assign ('_POST', $_POST);
  $render->assign ('_REQUEST', $_REQUEST);

  $render->assign('ctrl', $ctrl);
  //$render->assign('setting',InnoUtil::getSetting());
  $render->assign('user',   InnoUtil::getUserInfo());

  if ($lang){
    $render->assign('lang', $lang);
  }else{
    $render->assign('lang', pnUserGetLang());
  }
  $render->assign('access_edit', SecurityUtil::checkPermission('HotelBooking::', '::', ACCESS_COMMENT));
}

/**
 * Main user function . the user side page controller
 * @author Chayakon PONGSIRI
 * @return string HTML string
 */
function HotelBooking_user_main() {
    //_autoexecute();
    //return HotelBooking_user_list();
    return HotelBooking_user_page();
    
}

/**
* display page with out class loader
*/
function HotelBooking_user_page() {
    if(!pnUserLoggedIn()){
      return LogUtil::registerError ("You are not Logged in.");
    }
    
    $render = pnRender::getInstance('HotelBooking');
    
    return $render->fetch('user_page_home.htm');

}

/**
* display page with class that extend Object 
*/
function HotelBooking_user_view() {
    //_autoexecute();
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'view' , 'GET');
    //$id the id no if edit form
    $id      = FormUtil::getPassedValue ('id', null , 'GET');
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');
    $where   = '';

    $pagesize = pnModGetVar ('HotelBooking', 'pagesize') ? pnModGetVar ('HotelBooking', 'pagesize') : 10;
    $render = pnRender::getInstance('HotelBooking');
    
    if ($id){
      //load class
      if (!($class = Loader::loadClassFromModule ('HotelBooking',"User".$ctrl, false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();
      
      if (method_exists($object,'genFilter')){
        $wheres[] = $object->genFilter();
      }
      
      if(is_array($wheres)){
        $where = implode(" AND ",$wheres);
      }
      
      $object->getWhere($where);
      
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      if(count($object->_objData)<=0){
        return LogUtil::registerError ("You can't access this $ctrl.");
      }
      $render->assign ('view', $object->_objData);
    }
    _preRender($render);
    return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
}

/**
* display page with class that extend Object Array
*/
function HotelBooking_user_list() {
    $ctrl    = FormUtil::getPassedValue ('ctrl', 'hotelseason' , 'GET');
    $func  = FormUtil::getPassedValue ('func', 'list' , 'GET');
    $method  = FormUtil::getPassedValue ('method', '' , 'GET');
    $categories_id = FormUtil::getPassedValue ('categories_id', '' , 'GET');
    if($func == '' || $func == 'main'){
      $func  = 'list';
    }
    $is_export = false;
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    //echo $filter; exit;
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');
    
    if($ctrl===FALSE){
      return LogUtil::registerError ("Control is not assign...");
    }

    $pagesize = pnModGetVar ('HotelBooking', 'pagesize') ? pnModGetVar ('HotelBooking', 'pagesize') : 20;
    
    $render = pnRender::getInstance('HotelBooking');

    //check is export
    $export = FormUtil::getPassedValue ('export', false);
    $button_export = FormUtil::getPassedValue ('button_export', false);
    $button_export_x = FormUtil::getPassedValue ('button_export_x', false);
    if ($export || $button_export || $button_export_x){
      $is_export = true;
    }
    if (!($class = Loader::loadClassFromModule ('HotelBooking','User'.ucfirst($ctrl), true)))
      return LogUtil::registerError ("Unable to load class [User".ucfirst($ctrl)."] ...");

    $objectArray = new $class ();
    $where   = null;
    $sort = null;
    if (method_exists($objectArray,'genFilter')){
      $where = $objectArray->genFilter();
    }
    if (method_exists($objectArray,'genSort')){
      $sort = $objectArray->genSort();
    }
    if (method_exists($objectArray,'selectExtendResult')){
      $resultex = $objectArray->selectExtendResult();
      $render->assign('extendResult', $resultex);
    }
    if (empty($where)){
      $where = implode(' AND ',$objectArray->_objWhere);
    }else if (is_array($objectArray->_objWhere)){
      $where .= implode(' AND ',$objectArray->_objWhere);
    }else if (!empty($objectArray->_objWhere)){
      $where .= ' AND ' . $objectArray->_objWhere;
    }
    if (empty($sort)){
      $sort = $objectArray->_objSort;
    }

    //Spilt page
    $pager = array();
    $pager['numitems']     = $objectArray->getCount($where , true);
    $pager['itemsperpage'] = $pagesize;
    $render->assign ('startnum', $offset);
    $render->assign ('pager', $pager);

    $objectArray->get ($where, $sort , $offset, $pagesize);

    //assign to view
    $render->assign('objectArray', $objectArray->_objData);

    _preRender($render);

    return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');

}

function HotelBooking_user_form() {
    HotelBooking_user_permission();
    //$uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
    //$user    = InnoUtil::getUserInfo();
    //if ( $id && ((($uid == $user['uid']) && ($uid != '') && $uid ) || (intval($user['level']) == intval(constant('ADMIN_EDIT_LEVEL')) )) ) {
      //$ctrl the class name
      $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
      //$method the method of request for edit or view enum[ view | form | delete | list | page]
      $func  = FormUtil::getPassedValue ('func', 'form' , 'GET');
      //$id the id no if edit form
      $id      = FormUtil::getPassedValue ('id', null , 'GET');
      //pagnigation variable
      $filter  = FormUtil::getPassedValue ('filter', 0);
      $offset  = FormUtil::getPassedValue ('startnum', 0);
      $sort    = FormUtil::getPassedValue ('sort', '');
      $where   = '';

      $pagesize = pnModGetVar ('HotelBooking', 'pagesize') ? pnModGetVar ('HotelBooking', 'pagesize') : 100;
      $render = pnRender::getInstance('HotelBooking');
      $mode = null;
      //var_dump(Loader::loadClassFromModule ('HotelBooking',"User".ucfirst($ctrl), false));
      //load class
      if (!($class = Loader::loadClassFromModule ('HotelBooking',"User".ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [User".ucfirst($ctrl)."] ...");

      $object  = new $class ();

      if (!SecurityUtilEx::checkPermissionFromObject($object)){
        return LogUtil::registerError ("ʨǹ�թ�١�ӡѴ㋩㪩䴩੾ҐʁҪԡ෨ҹѩ�");
      }
      if (method_exists($object,'genPermission')){
        $permit = $object->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ʨǹ�թ�١�ӡѴ㋩㪩䴩੾ҐʁҪԡ෨ҹѩ�");
        }
      }
      if ($id && $object){

        $object->get($id);

        $mode = 'edit';  
        $render->assign ('form', $object->_objData);
        
      }else{
        $mode = 'new';
      }
      $render->assign ('mode', $mode);
      
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      _preRender($render);
      return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
    //}
}

/**
* for delete object for database by specify id
*/
function HotelBooking_user_delete() {
    //HotelBooking_user_permission();
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    $id      = FormUtil::getPassedValue ('id', false , 'GET');
    $forward = FormUtil::getPassedValue ('forward', false , 'GET');

    $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
    $user    = InnoUtil::getUserInfo();

      //load class
      if (!($class = Loader::loadClassFromModule ('HotelBooking', ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [".ucfirst($ctrl)."] ...");

      $object  = new $class ();
      $object->_objData[$object->_objField] = $id;
      $object->delete();
      
      if (method_exists($object,'genForward')){
        $forward_url = $object->genForward();
      }else if (!is_array($forward) && $forward){
        $forward_url =  str_replace("&amp;", "&", $forward);
      }else if (is_array($forward)){
        $forward_url = InnoUtil::createUrlFromArray($forward);
      }else{
        $forward_url = pnModURL('HotelBooking', 'user', 'list' , array('ctrl'=>$ctrl));
      }
      pnRedirect($forward_url);
      die;

}


function HotelBooking_user_fileupload(){
  if(!pnUserLoggedIn()){
    return LogUtil::registerError ("You are not Logged in.");
  }
  
  $uid = SessionUtil::getVar('uid');
  $hotelID = FormUtil::getPassedValue('hotelid',FALSE);
 
  if (!($class = Loader::loadClassFromModule ('HotelBooking',"UserHotelmember", false)))
      return LogUtil::registerError ("Unable to load class [UserHotelmember] ...");

  if(!$hotelID){
    $object  = new $class ();
    $where = $object->_columns['cr_uid']."  = ".$uid;
    $object->getWhere($where);
    $hotelID = $object->_objData[id];
  }
  
  // HTTP headers for no cache etc
  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
  
  $dir_1 = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."resource";
  $dir_2 = $dir_1.DIRECTORY_SEPARATOR."hotelbooking_upload";
  
  if (!file_exists($dir_1))
  	@mkdir($dir_1);
  if (!file_exists($dir_2))
  	@mkdir($dir_2);
  
  // Settings
  $targetDir = $dir_2.DIRECTORY_SEPARATOR.$hotelID;
  //$targetDir = 'uploads';
  $cleanupTargetDir = true; // Remove old files
  $maxFileAge = 5 * 3600; // Temp file age in seconds
  
  // 5 minutes execution time
  @set_time_limit(5 * 60);
  
  // Uncomment this one to fake upload time
  // usleep(5000);
  
  // Get parameters
  $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
  $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  
  // Clean the fileName for security reasons
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
  
  // Make sure the fileName is unique but only if chunking is disabled
  if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
  	$ext = strrpos($fileName, '.');
  	$fileName_a = substr($fileName, 0, $ext);
  	$fileName_b = substr($fileName, $ext);
  
  	$count = 1;
  	while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
  		$count++;
  
  	$fileName = $fileName_a . '_' . $count . $fileName_b;
  }
  
  $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
  
  // Create target dir
  if (!file_exists($targetDir))
  	@mkdir($targetDir);
  
  // Remove old temp files	
  if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
  	while (($file = readdir($dir)) !== false) {
  		$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  
  		// Remove temp file if it is older than the max age and is not the current file
  		if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
  			@unlink($tmpfilePath);
  		}
  	}
  
  	closedir($dir);
  } else
  	die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  	
  
  // Look for the content type header
  if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
  	$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  
  if (isset($_SERVER["CONTENT_TYPE"]))
  	$contentType = $_SERVER["CONTENT_TYPE"];
  
  // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
  if (strpos($contentType, "multipart") !== false) {
  	if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  		// Open temp file
  		$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
  		if ($out) {
  			// Read binary input stream and append it to temp file
  			$in = fopen($_FILES['file']['tmp_name'], "rb");
  
  			if ($in) {
  				while ($buff = fread($in, 4096))
  					fwrite($out, $buff);
  			} else
  				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  			fclose($in);
  			fclose($out);
  			@unlink($_FILES['file']['tmp_name']);
  		} else
  			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  	} else
  		die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  } else {
  	// Open temp file
  	$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
  	if ($out) {
  		// Read binary input stream and append it to temp file
  		$in = fopen("php://input", "rb");
  
  		if ($in) {
  			while ($buff = fread($in, 4096))
  				fwrite($out, $buff);
  		} else
  			die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  
  		fclose($in);
  		fclose($out);
  	} else
  		die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  }
  
  // Check if file has been uploaded
  if (!$chunks || $chunk == $chunks - 1) {
  	// Strip the temp .part suffix off 
  	rename("{$filePath}.part", $filePath);
    
    Loader::loadClass('SimpleImage', "modules/HotelBooking/pnincludes");
    
    $ext = strrpos($filePath, '.');
  	$fileName_a = substr($filePath, 0, $ext);
  	$fileName_b = substr($filePath, $ext);
    
   
    
    
    $filePath_S = $fileName_a."_s_".$fileName_b;
    $filePath_M = $fileName_a."_m_".$fileName_b;
    $filePath_L = $fileName_a."_l_".$fileName_b;
    $filePath_O = $filePath;
    
    $fileName_S = str_replace($targetDir."\\","",$filePath_S);
    $fileName_M = str_replace($targetDir."\\","",$filePath_M);
    $fileName_L = str_replace($targetDir."\\","",$filePath_L);
    $fileName_O = str_replace($targetDir."\\","",$filePath);
    
    $fileURL_S = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_S;
    $fileURL_M = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_M;
    $fileURL_L = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_L;
    $fileURL_O = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_O;
    
    $imageS = new SimpleImage();
    $imageS->load($filePath);
    $imageS->resizeToWidth(150);
    $imageS->save($filePath_S);
    
    $imageM = new SimpleImage();
    $imageM->load($filePath);
    $imageM->resizeToWidth(300);
    $imageM->save($filePath_M);
    
    $imageL = new SimpleImage();
    $imageL->load($filePath);
    $imageL->resizeToWidth(600);
    $imageL->save($filePath_L);
    
    $imageObj = array(
                        'hotelMember_id'=> $hotelID,
                        's_fileName' => $fileName_S,
                        'm_fileName' => $fileName_M,
                        'l_fileName' => $fileName_L,
                        'o_fileName' => $fileName_O,
                        's_path' => $filePath_S,
                        'm_path' => $filePath_M,
                        'l_path' => $filePath_L,
                        'o_path' => $filePath_O,
                        's_url' => $fileURL_S,
                        'm_url' => $fileURL_M,
                        'l_url' => $fileURL_L,
                        'o_url' => $fileURL_O
                      );
    
    if (!($class2 = Loader::loadClassFromModule ('HotelBooking',"UserHotelimages", false)))
      return LogUtil::registerError ("Unable to load class [UserhHoteliImages] ...");
      
    $objectImages  = new $class2();
    $objectImages->_objData = $imageObj;
    $objectImages->insert();
  }
  
  
  // Return JSON-RPC response
  die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  
}

function HotelBooking_user_roomimagesupload(){
  if(!pnUserLoggedIn()){
    return LogUtil::registerError ("You are not Logged in.");
  }
  
  $uid = SessionUtil::getVar('uid');
  $hotelID = FormUtil::getPassedValue('hotelid',FALSE);
 
  if (!($class = Loader::loadClassFromModule ('HotelBooking',"UserHotelmember", false)))
      return LogUtil::registerError ("Unable to load class [UserHotelmember] ...");

  if(!$hotelID){
    $object  = new $class ();
    $where = $object->_columns['cr_uid']."  = ".$uid;
    $object->getWhere($where);
    $hotelID = $object->_objData[id];
  }
  
  // HTTP headers for no cache etc
  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
  
  $dir_1 = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."resource";
  $dir_2 = $dir_1.DIRECTORY_SEPARATOR."hotelbooking_upload";
  
  if (!file_exists($dir_1))
  	@mkdir($dir_1);
  if (!file_exists($dir_2))
  	@mkdir($dir_2);
  
  // Settings
  $targetDir = $dir_2.DIRECTORY_SEPARATOR.$hotelID;
  //$targetDir = 'uploads';
  $cleanupTargetDir = true; // Remove old files
  $maxFileAge = 5 * 3600; // Temp file age in seconds
  
  // 5 minutes execution time
  @set_time_limit(5 * 60);
  
  // Uncomment this one to fake upload time
  // usleep(5000);
  
  // Get parameters
  $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
  $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  
  // Clean the fileName for security reasons
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
  
  // Make sure the fileName is unique but only if chunking is disabled
  if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
  	$ext = strrpos($fileName, '.');
  	$fileName_a = substr($fileName, 0, $ext);
  	$fileName_b = substr($fileName, $ext);
  
  	$count = 1;
  	while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
  		$count++;
  
  	$fileName = $fileName_a . '_' . $count . $fileName_b;
  }
  
  $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
  
  // Create target dir
  if (!file_exists($targetDir))
  	@mkdir($targetDir);
  
  // Remove old temp files	
  if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
  	while (($file = readdir($dir)) !== false) {
  		$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  
  		// Remove temp file if it is older than the max age and is not the current file
  		if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
  			@unlink($tmpfilePath);
  		}
  	}
  
  	closedir($dir);
  } else
  	die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  	
  
  // Look for the content type header
  if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
  	$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  
  if (isset($_SERVER["CONTENT_TYPE"]))
  	$contentType = $_SERVER["CONTENT_TYPE"];
  
  // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
  if (strpos($contentType, "multipart") !== false) {
  	if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  		// Open temp file
  		$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
  		if ($out) {
  			// Read binary input stream and append it to temp file
  			$in = fopen($_FILES['file']['tmp_name'], "rb");
  
  			if ($in) {
  				while ($buff = fread($in, 4096))
  					fwrite($out, $buff);
  			} else
  				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  			fclose($in);
  			fclose($out);
  			@unlink($_FILES['file']['tmp_name']);
  		} else
  			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  	} else
  		die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  } else {
  	// Open temp file
  	$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
  	if ($out) {
  		// Read binary input stream and append it to temp file
  		$in = fopen("php://input", "rb");
  
  		if ($in) {
  			while ($buff = fread($in, 4096))
  				fwrite($out, $buff);
  		} else
  			die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  
  		fclose($in);
  		fclose($out);
  	} else
  		die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  }
  
  // Check if file has been uploaded
  if (!$chunks || $chunk == $chunks - 1) {
  	// Strip the temp .part suffix off 
  	rename("{$filePath}.part", $filePath);
    
    Loader::loadClass('SimpleImage', "modules/HotelBooking/pnincludes");
    
    $ext = strrpos($filePath, '.');
  	$fileName_a = substr($filePath, 0, $ext);
  	$fileName_b = substr($filePath, $ext);
    
   
    
    
    $filePath_S = $fileName_a."_s_".$fileName_b;
    $filePath_M = $fileName_a."_m_".$fileName_b;
    $filePath_L = $fileName_a."_l_".$fileName_b;
    $filePath_O = $filePath;
    
    $fileName_S = str_replace($targetDir."\\","",$filePath_S);
    $fileName_M = str_replace($targetDir."\\","",$filePath_M);
    $fileName_L = str_replace($targetDir."\\","",$filePath_L);
    $fileName_O = str_replace($targetDir."\\","",$filePath);
    
    $fileURL_S = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_S;
    $fileURL_M = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_M;
    $fileURL_L = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_L;
    $fileURL_O = "http://".$_SERVER["SERVER_NAME"]."/resource/hotelbooking_upload/".$hotelID."/".$fileName_O;
    
    $imageS = new SimpleImage();
    $imageS->load($filePath);
    $imageS->resizeToWidth(150);
    $imageS->save($filePath_S);
    
    $imageM = new SimpleImage();
    $imageM->load($filePath);
    $imageM->resizeToWidth(300);
    $imageM->save($filePath_M);
    
    $imageL = new SimpleImage();
    $imageL->load($filePath);
    $imageL->resizeToWidth(600);
    $imageL->save($filePath_L);
    
    $imageObj = array(
                        'hotelMember_id'=> $hotelID,
                        's_fileName' => $fileName_S,
                        'm_fileName' => $fileName_M,
                        'l_fileName' => $fileName_L,
                        'o_fileName' => $fileName_O,
                        's_path' => $filePath_S,
                        'm_path' => $filePath_M,
                        'l_path' => $filePath_L,
                        'o_path' => $filePath_O,
                        's_url' => $fileURL_S,
                        'm_url' => $fileURL_M,
                        'l_url' => $fileURL_L,
                        'o_url' => $fileURL_O
                      );
    
    if (!($class2 = Loader::loadClassFromModule ('HotelBooking',"UserHotelimages", false)))
      return LogUtil::registerError ("Unable to load class [UserhHoteliImages] ...");
      
    $objectImages  = new $class2();
    $objectImages->_objData = $imageObj;
    $objectImages->insert();
  }
  
  
  // Return JSON-RPC response
  die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  
}


function HotelBooking_user_listallotment(){
  if(!pnUserLoggedIn()){
    return LogUtil::registerError ("You are not Logged in.");
  }

  $uid = SessionUtil::getVar('uid');
  $hotelID = FormUtil::getPassedValue('hotelid',FALSE);
  
  $baseYear = FormUtil::getPassedValue('year',date('Y',strtotime("now")));
  $baseMonth = FormUtil::getPassedValue('month',date('m',strtotime("now")));
  
  $render = pnRender::getInstance('HotelBooking');
  _preRender($render);
  
  if((intval($baseYear)&&intval($baseMonth))){
    $dateMonth = array(
                    $baseYear => array(
                                      date('F',mktime(0,0,0,1,1,$baseYear))=>date('t',mktime(0,0,0,1,1,$baseYear)),
                                      date('F',mktime(0,0,0,2,1,$baseYear))=>date('t',mktime(0,0,0,2,1,$baseYear)),
                                      date('F',mktime(0,0,0,3,1,$baseYear))=>date('t',mktime(0,0,0,3,1,$baseYear)),
                                      date('F',mktime(0,0,0,4,1,$baseYear))=>date('t',mktime(0,0,0,4,1,$baseYear)),
                                      date('F',mktime(0,0,0,5,1,$baseYear))=>date('t',mktime(0,0,0,5,1,$baseYear)),
                                      date('F',mktime(0,0,0,6,1,$baseYear))=>date('t',mktime(0,0,0,6,1,$baseYear)),
                                      date('F',mktime(0,0,0,7,1,$baseYear))=>date('t',mktime(0,0,0,7,1,$baseYear)),
                                      date('F',mktime(0,0,0,8,1,$baseYear))=>date('t',mktime(0,0,0,8,1,$baseYear)),
                                      date('F',mktime(0,0,0,9,1,$baseYear))=>date('t',mktime(0,0,0,9,1,$baseYear)),
                                      date('F',mktime(0,0,0,10,1,$baseYear))=>date('t',mktime(0,0,0,10,1,$baseYear)),
                                      date('F',mktime(0,0,0,11,1,$baseYear))=>date('t',mktime(0,0,0,11,1,$baseYear)),
                                      date('F',mktime(0,0,0,12,1,$baseYear))=>date('t',mktime(0,0,0,12,1,$baseYear))
                                    )
    );
    foreach($dateMonth as $year=>$monthArray){
      foreach($monthArray as $month=>$date){
        for($i=1;$i<=$date;$i++){
          $finalDate[$year][$month][$i] = date('l',strtotime("$i $month $year"));
        }
      }
    }
    unset($dateMonth);
  }

  if (!($class = Loader::loadClassFromModule ('HotelBooking',"UserHotelmember", false)))
      return LogUtil::registerError ("[753] Unable to load class [UserHotelmember] ...");

  if(!$hotelID){
    $object  = new $class ();
    $where = $object->_columns['cr_uid']." = ".$uid;
    $object->getWhere($where);
    $hotelID = $object->_objData[id];
  }
  if(!isset($hotelID)){
    return LogUtil::registerError ("Unable to load hotel description.");
  }
  if (!($class = Loader::loadClassFromModule ('HotelBooking',"UserHotelallotment", TRUE)))
    return LogUtil::registerError ("Unable to load class [UserHotelallotment] ...");
  
  $objectArray  = new $class ();
  $wheres[] = $objectArray->_columns['hotelMember_id']." = ".$hotelID;
  $wheres[] = $objectArray->_columns['date']." between  '$baseYear-$baseMonth-01' and '$baseYear-$baseMonth-".date('t',mktime(0,0,0,date('m',strtotime("$baseMonth")),1,$baseYear))."'";
  
  $where = implode(" and ", $wheres);
  $objectArray->get($where);

  if($baseMonth==12){
    $render->assign("nextMonth",1);
    $render->assign("nextYear",$baseYear+1);
  }else{
    $render->assign("nextMonth",$baseMonth+1);
    $render->assign("nextYear",$baseYear);
  }
  
  if($baseMonth==1){
    $render->assign("previousMonth",12);
    $render->assign("previousYear",$baseYear-1);
  }else{
    $render->assign("previousMonth",$baseMonth-1);
    $render->assign("previousYear",$baseYear);
  }
  
  $render->assign("currentMonth",sprintf("%1$02d",$baseMonth));
  $render->assign("currentYear",$baseYear);
  
  if($objectArray->_objData != NULL){
    $result['allotments'] = $objectArray->getData();
    
    $render->assign("status","edit");
    foreach($result['allotments'] AS $allotment){
      $data = $allotment["date"];
      $year = substr($data,0,4);
      $month = substr($data,5,2);
      $day = substr($data,8,2);
      $resultData[$allotment['hotelRoom_id']][$year][$month][$day]["allotment"] = $allotment["available"];
      $resultData[$allotment['hotelRoom_id']][$year][$month][$day]["id"] = $allotment["id"];
    }
    $render->assign("strMonth",date('F',mktime(0,0,0,$baseMonth,1,$baseYear)));
    $newMonth[date('F',mktime(0,0,0,$baseMonth,1,$baseYear))] = $finalDate[$baseYear][date('F',mktime(0,0,0,$baseMonth,1,$baseYear))];
    $render->assign("dateList",$newMonth);
    //var_dump($resultData);exit;
    $render->assign("dateAollotmentList",$resultData);
  }else{
    
    $render->assign("status","new");
    $newMonth[date('F',mktime(0,0,0,$baseMonth,1,$baseYear))] = $finalDate[$baseYear][date('F',mktime(0,0,0,$baseMonth,1,$baseYear))];
    $render->assign("dateList",$newMonth);
  }
  
  return $render->fetch('user_list_hotelallotment.htm');
}















